<?php
namespace NewIdiom\Controller;
use  Common\Controller\NewIdiomController;
//版本2
class RevisionController extends NewIdiomController {

    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     * 广告 （完成）
     */
    public function advertising(){

        $appid = I('post.appid','','htmlspecialchars');

        $ad = M('newidiom_appshow')->field('appid,url,envversion,logo,isshow,category,location')->select();

        foreach ($ad as $key=>$value){

            $ad[$key]['logo'] = $this->url.$ad[$key]['logo'];
        }

        $this->returnData($ad);
    }

    /**
     * 排行
     */
    public function ranking(){

        $member_id = I('post.member_id','','int');
        $state = I('post.state','','int');
        $rank = "";
        //本周排行
        if ($state=='1'){

            $rank = $this->getcacheweek2();
            $this->returnData($rank,'成功','200');
        }

        //好友排行
        if ($state=='2'){

            $where['my_member_id'] = $member_id;

            $coupling_uids = M('newidiom_relationship')->where($where)->getField('coupling_member_id',true);
            if (empty($coupling_uids)){
                $coupling_uids = array();
            }
            $coupling_uids[] = $member_id;


            $uids = M('newidiom_relationship')->where(array('coupling_member_id'=>$member_id))->getField('my_member_id',true);
            if (empty($uids)){
                $uids = array();
            }

            $ids = array_unique(array_merge($coupling_uids,$uids));//合并去重

            $where1['uid'] = array('in',$ids);

            if ($ids){
                $rank = M('newidiom_member')->field('nickname,avatarurl,customs')->where($where1)->limit(100)->order('customs desc')->select();
                $this->returnData($rank,'成功','200');
            }

        }

    }

    /**
     * 微信群分享看答案
     */
    public function sharerecord(){

        $member_id = I('post.member_id','','int');

        $encryptedData = $_POST['encryptedData'];
        $iv = $_POST['iv'];


        if (!$encryptedData||!$member_id||!$iv){
            $this->returnData('','参数错误',401);
        }

        $info = M('newidiom_member')->field('appid,session_key')->where(array('uid'=>$member_id))->find();

        $appid = $info['appid'];
        $sessionkey = $info['session_key'];

        $openGId = $this->getopenGId($appid,$sessionkey,$encryptedData,$iv);

        if ($openGId=='-1'){
            $this->returnData('','分享失败',100);
        }

        $time = date('Y-m-d',time());

        $where['sharetime'] = $time;
        $where['uid'] 		= $member_id;
        $where['opengid'] 	= $openGId;


        $record = M('newidiom_wechat_group')->where($where)->getField('sharenum'); //判断是否已分享


        if ($record>=3){
            $this->returnData(array('repetition'=>'out'),'同群有效分享次数为5',201);
        }

        //如果已分享则自增分享次数然后返回
        if ($record){
            M('newidiom_wechat_group')->where($where)->setInc('sharenum');

            $this->returnData(array('repetition'=>'no'),'分享成功',200);
        }


        $data = array(
            'opengid'=>$openGId,
            'sharetime'=>$time,
            'sharenum'=>1,
            'uid'=>$member_id,
        );

        M('newidiom_wechat_group')->data($data)->add();

        $this->returnData(array('repetition'=>'no'),'分享成功',200);
    }


    /**
     * 获取题目进行挑战 （完成）
     */
    public function chang(){

        $member_id = I('post.member_id','','int');
        $state = I('post.state','','int');

        if (!$member_id){
            $this->returnData('','参数错误',401);
        }

        //挑战次数限制 (member_data  中的参数对下面的程序很重要)
        $today_time     =   strtotime(date('Y-m-d'));
        $field_member   =   array('uid','customs','play_time','play_num');
        $member_data    =   M('newidiom_member')->where(array('uid'=>$member_id))->field($field_member)->find();
        if (empty($member_data))
        {
            $this->returnData('','参数错误,user is not exit',401);
        }

        if ($member_data['play_time'] >= $today_time && $member_data['play_num'] >= 10)
        {
            $this->returnData('','当天挑战次数达上限,明天再来',401);
        }

        //一次取20题
        $nextcustoms = 5;

        if ($state=='2')
        {
            $sort = I('post.sort','','int');
            if (!$sort){
                $this->returnData('','参数错误',401);
            }

            $question = M('newidiom_questions')->limit($sort,$nextcustoms)->order('sort asc')->select();

            foreach ($question as $key=>$value){

                $question[$key]['imgsrc'] = $this->url.$question[$key]['imgsrc'];
            }
            //设置奖励判断记录
            if (! empty($question))
            {
                $this->set_record($member_data);
            }

            $this->returnData($question);
        }

        $customs    = $member_data['customs'];

        $question   = M('newidiom_questions')->limit($customs,$nextcustoms)->order('sort asc')->select();

        foreach ($question as $key=>$value){

            $question[$key]['imgsrc'] = $this->url.$question[$key]['imgsrc'];
        }

        $count = M('newidiom_questions')->count();

        //设置奖励判断记录
        if (! empty($question))
        {
            $this->set_record($member_data);
        }

        $this->returnData($question,$count);
    }


    /**
     * 答题 （完成）
     */
    public function inanswer(){
        $data                   =   array();
        $data['challenge_id']   =   false;
        $data['msg']            =   '答对了';
        $data['type']           =   1;
        $member_id              =   I('post.member_id','','int');

        $state = I('post.state','','int');

        if (!$member_id||!$state){
            $this->returnData('','参数错误',401);
        }

        $nowweek = (int)date('W');
        $year = date('Y');

        $where = array(
            'year'=>$year,
            'week'=>$nowweek,
            'uid'=>$member_id,
        );

        //判断当周是否有挑战记录
        $ischange = M('newidiom_week')->field('id')->where($where)->find();
        if ($ischange){
            M('newidiom_week')->where($where)->setInc('customs');//当周分数加一

            M('newidiom_week')->where($where)->save(array('exittime'=>date('Y-m-d H:i:s')));
        }else{
            $where['createtime'] = date('Y-m-d H:i:s');
            $where['exittime'] = date('Y-m-d H:i:s');
            $where['customs'] = 1;
            M('newidiom_week')->data($where)->add();
        }
        M('newidiom_member')->where(array('id'=>$member_id))->setInc('customs'); //分数加一

        //判断答对次数奖励红包
        $field_member   =   array('customs','redbag_customs');
        $member_data    =   M('newidiom_member')->where(array('uid'=>$member_id))->field($field_member)->find();
        if (! empty($member_data))
        {
            //通关成功！
            if ($member_data['customs'] == $member_data['redbag_customs'])
            {
                //获取红包
                $data['challenge_id']   =   $this->create_redbag($member_id);
                $data['msg']            =   '恭喜你通过所有关卡';
                $data['type']           =   2;
            }
        }

        $this->returnData($data,'成功',200);
    }


    /**
     * 好友关联 （完成）
     */
    public function friendsassociated(){

        $uid = I('post.my_member_id','','int');
        $coupling_uid = I('post.coupling_member_id','','int');
        $appid = I('post.appid','','htmlspecialchars');

        if ($uid==""||$coupling_uid==""){
            $this->returnData('','参数不能为空',401);
        }

        if ($uid==$coupling_uid){
            $this->returnData('','自己不用关联自己',100);
        }


        $where['my_member_id']=$uid;
        $where['coupling_member_id']=$coupling_uid;
        $where['appid'] = $appid;

        $where1['my_member_id']=$coupling_uid;
        $where1['coupling_member_id']=$uid;
        $where1['appid'] = $appid;

        $relevancy = M('newidiom_relationship')->field('id')->where($where)->find();

        $relevancy1 = M('newidiom_relationship')->field('id')->where($where1)->find();
        //判断是否已关联(有待优化)
        if ($relevancy||$relevancy1){
            $this->returnData('','已关联',200);
        }

        $data = array(
            'my_member_id'=>$uid,
            'coupling_member_id' =>$coupling_uid,
            'appid'=>$appid,
            'createtime' =>time(),
        );

        $insert = M('newidiom_relationship')->data($data)->add();

        if ($insert){
            $this->returnData('','关联成功',200);
        }else{
            $this->returnData('','关联失败',100);
        }

    }

    /**
     * 设置当前玩的记录数 （完成）
     */
    private function set_record($member_data)
    {
        $where          =   array();
        $where['uid']   =   $member_data['uid'];
        $today_time     =   strtotime(date('Y-m-d'));
        $update_data    =   array();
        if ($member_data['play_time'] < $today_time)
        {
            $update_data['play_time']   =   time();
            $update_data['play_num']    =   1;
        }
        else
        {
            $update_data['play_time']   =   time();
            $update_data['play_num']    =   $member_data['play_num'] + 1;
        }
        $update_data['redbag_customs']  =   $member_data['customs'] + 5;     //达到改关数才能奖励红包

        M('newidiom_member')->where($where)->save($update_data);
    }

    /**
     * 获取红包
     */
    public function award_total()
    {
        $uid                =   I('post.uid','','htmlspecialchars');
        $challenge_id       =   I('post.challenge_id','','htmlspecialchars');

        if (! empty($challenge_id) && ! empty($uid))
        {
            $data                   =   array();
            $where                  =   array();
            $field                  =   array('red_total','status','total_sn','create_time','red_total');
            $where['uid']           =   $uid;
            $where['challenge_id']  =   $challenge_id;
            $newsong_redbag         =   M('newidiom_redbag')->where($where)->field($field)->find();
            if (! empty($newsong_redbag))
            {
                //更新数据
                if (empty($newsong_redbag['status']))
                {
                    $where_member           =   array();
                    $field                  =   array('money_total','total_money');
                    $where_member['uid']    =   $uid;
                    $member_data            =   M('newidiom_member')->where($where_member)->field($field)->find();

                    if (! empty($member_data))
                    {
                        //开启事务更新数据
                        $Model = M();
                        $Model->startTrans();

                        //更新红包
                        $update_redbag                  =   array();
                        $update_redbag['status']        =   1;
                        $update_redbag['update_time']   =   date('Y-m-d H:i:s');

                        $result     =  $Model->table('mj_newidiom_redbag')->where($where)->save($update_redbag);
                        if (! empty($result))
                        {
                            //更新红包记录
                            $update_log                  =   array();
                            $update_log['status']        =   1;
                            $update_log['update_time']   =   date('Y-m-d H:i:s');
                            $result     =   $Model->table('mj_newidiom_redbag_log')->where($where)->save($update_log);

                            if (! empty($result))
                            {
                                //更新用户数据
                                $update_member                  =   array();
                                $update_member['money_total']   =   $member_data['money_total'] + $newsong_redbag['red_total'];
                                $update_member['total_money']   =   $member_data['total_money'] + $newsong_redbag['red_total'];
                                $update_member['updatetime']    =   time();
                                $result     =   $Model->table('mj_newidiom_member')->where($where_member)->save($update_member);

                                if (! empty($result))
                                {
                                    //更新收支记录
                                    $where_change_log                   =   array();
                                    $where_change_log['from_sn']        =   $newsong_redbag['total_sn'];
                                    $update_change_log                  =   array();
                                    $update_change_log['status']        =   1;
                                    $update_change_log['update_time']   =   date('Y-m-d H:i:s');
                                    $Model->table('mj_newidiom_change_log')->where($where_member)->save($update_change_log);
                                    $Model->commit();
                                }
                                else
                                {
                                    $Model->rollback();
                                }
                            }
                            else
                            {
                                $Model->rollback();
                            }
                        }
                        else
                        {
                            $Model->rollback();
                        }

                    }
                }

                $data               =   $newsong_redbag['red_total'];
                $this->returnData($data,$msg='ok',$code=200);
            }
        }
    }
}